<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\api\validate\Bank as BankValidate;
use app\common\model\Bank as BankModel;
use think\Db;
use think\Exception;

class Bank extends Api
{
    protected $noNeedRight = '*';

    /**
     * 银行卡列表
     */
    public function lists()
    {
        $data = BankModel::where('user_id', $this->auth->id)->select();
        $this->success('获取成功', $data);
    }

    /**
     * 银行卡详情
     */
    public function detail()
    {
        $data = BankModel::get($this->request->get('id'));
        $this->success('获取成功', $data);
    }

    /**
     * 添加银行卡
     */
    public function add()
    {
        $data = $this->request->post();

        $validate = validate(BankValidate::class);
        if (!$validate->scene('add')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            BankModel::create([
                'user_id' => $this->auth->id,
                'holder' => $data['holder'],
                'bank' => $data['bank'],
                'subbranch' => $data['subbranch'],
                'account' => $data['account']
            ]);
            Db::commit();
            $this->success('添加成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 编辑银行卡
     */
    public function edit()
    {
        $data = $this->request->post();

        $validate = validate(BankValidate::class);
        if (!$validate->scene('edit')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            $bank = new BankModel();
            $bank->save([
                'holder' => $data['holder'],
                'bank' => $data['bank'],
                'subbranch' => $data['subbranch'],
                'account' => $data['account']
            ], ['id' => $data['id']]);
            Db::commit();
            $this->success('编辑成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 删除银行卡
     */
    public function del()
    {
        $data = $this->request->post();

        $validate = validate(BankValidate::class);
        if (!$validate->scene('del')->check($data)) {
            $this->error($validate->getError());
        }

        Db::startTrans();
        try {
            BankModel::destroy($data['id']);
            Db::commit();
            $this->success('删除成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
}